<template>
  <el-dialog
    title="数据上传"
    :visible.sync="visible"
    width="760px"
    center
    :before-close="handleClose"
  >
    <div class="file-upload-box">
      <el-upload
        :action="url"
        :accept="accept"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :file-list="fileList"
        :multiple="false"
        :auto-upload="false"
        style="width: 200px"
      >
        <el-button style="height: 40px" size="small" type="success"
          >选择文件</el-button
        >
        <div slot="tip" class="el-upload__tip">只能上传excel格式</div>
      </el-upload>
      <el-button
        size="small"
        style="height: 40px"
        type="primary"
        @click="submitUpload"
      >
        开始上传
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fileUploadApi, ledgerUpload } from "@api/projectManaApi";

export default {
  name: "fileUpload",
  props: ["visible", "curType", "statusType"],
  data() {
    return {
      fileList: [],
      url: "",
      accept: ".xls,.xlsx",
    };
  },
  created(){
    this.fileList = []
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove() {
      this.fileList = [];
    },
    async submitUpload() {
      if (this.fileList.length === 0)
        return this.$message.error("请选选择文件");
      const formData = new FormData();
      this.fileList.forEach((file) => {
        formData.append("file", file.raw);
      });
      let res;
      if (this.curType === "台账") {
        formData.append("status", this.statusType);
        res = await ledgerUpload(formData);
      }
      if (this.curType === "项目" || this.curType === 'startSign') {
        res = await fileUploadApi(formData);
      }
      if (res.code === 200) {
        this.$message.success("上传成功");
        if (this.curType === "项目" || this.curType === 'startSign') {
          this.fileList = []
          this.$emit("close", res.fileName);
        } else {
          this.handleClose("update");
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    handleClose(type) {
      this.fileList = []
      this.$emit("close", type);
    },
  },
};
</script>
<style scoped lang="less">
.file-upload-box {
  height: 300px;
  display: flex;
}
</style>
